from rest_framework.views import APIView
from rest_framework.response import Response
from utilss.response import APIResponse
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from . import serializers


class PayAPIView(APIView):
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]

    def post(self, request, *args, **kwargs):
        # 校验订单，生成订单编号
        print(request.data)
        serializer = serializers.OrderModelSerializer(data=request.data, context={"request": request})
        # 信息校验
        if serializer.is_valid(raise_exception=True):
            print(serializer.pay_url)

            # 生成订单编号,保存到数据库中
            serializer.save()
        # 返回支付宝url请求数据
        return Response(data=serializer.pay_url)
        # return Response(3)


from libs.iPay import alipay
from . import models
from utilss.loggings import logger


class SuccessAPIView(APIView):
    # 重点：要不要做登录认证，不需要：订单号可以获取你所需要的所有信息、回调参数有自己的安全校验、支付宝永远不可能通过token

    def patch(self, request, *args, **kwargs):
        print(request.query_params)
        data = request.query_params.dict()

        # 移除sign进行校验
        sign = data.pop('sign')
        # 进行校验
        result = alipay.verify(data, sign)

        if result:
            # 获取订单号
            # out_trade_no = data.get("out_trade_no")
            # # 获取流水号
            #
            # trade_no = data.get("trade_no")
            # print(f"{out_trade_no}订单完成支付流水号{trade_no}")
            # logger.warning(f"{out_trade_no}订单完成支付流水号{trade_no}")

            # 一般不进行回调直接操作订单状态
            pass
            # models.order.object.filter(out_trade_no=data.get('out_trade_no').update(order_status=1)
            # try:
            #     order = models.Order.objects.get(out_trade_no=out_trade_no)
            #     if order.order_status != 1:
            #         order.order_status = 1
            #         order.trade_no = trade_no
            #         order.save()
            #
            #         logger.warning(f"{out_trade_no}订单完成支付流水号{trade_no}")
            #     return Response("success")
            # except:
            #     pass
        return Response("同步回调完成")

    def post(self, request, *args, **kwargs):
        # 回调参数，是querydict类型,不能直接调用pop方法
        data = request.data.dict()
        # 移除签名
        sign = data.sign("sign")
        # 获取订单号
        out_trade_no = data.get("out_trade_no")
        # 获取流水号

        trade_no = data.get("trade_no")
        # 获取流水号
        result = alipay.verify(data, sign)

        if result and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            try:
                order = models.Order.objects.get(out_trade_no=out_trade_no)
                if order.order_status != 1:
                    order.order_status = 1
                    order.trade_no = trade_no
                    order.save()

                    logger.warning(f"{out_trade_no}订单完成支付流水号{trade_no}")
                return Response("success")
            except:
                pass
        return Response("failed")
